package com.bootdo.fx.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bootdo.common.utils.*;
import com.bootdo.fx.dao.UserInfoDao;
import com.bootdo.fx.domain.UserAddressDO;
import com.bootdo.fx.domain.UserInfoDO;
import com.bootdo.fx.service.UserAddressService;
import com.bootdo.fx.service.UserInfoService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.fx.domain.OrderInfoDO;
import com.bootdo.fx.service.OrderInfoService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * app_goods_order
 * 
 * @author 袁飞龙
 * @email 1992lcg@163.com
 * @date 2017-11-30 17:12:20
 */
 
@Controller
public class OrderInfoController {
	@Autowired
	private OrderInfoService orderInfoService;

	@Autowired
	private UserInfoService userInfoService;

	@Autowired
	private UserAddressService userAddressService;

	
	@GetMapping("/fx/orderInfo")
	@RequiresPermissions("fx:orderInfo:orderInfo")
	String orderInfo(){
	    return "fx/orderInfo/orderInfo";
	}

	/**
	 * 订单详情
	 * @param orderId
	 * @param model
	 * @return
	 */
	@GetMapping("/fx/orderInfo/orderDetail/{orderId}")
	@RequiresPermissions("fx:orderInfo:orderDetail")
	String orderDetail(@PathVariable("orderId") long orderId,Model model){
		OrderInfoDO orderInfo = orderInfoService.get(orderId);
		model.addAttribute("orderInfo", orderInfo);
		return "fx/orderInfo/orderDetail";
	}
	
	@ResponseBody
	@GetMapping("/fx/orderInfo/list")
	@RequiresPermissions("fx:orderInfo:orderInfo")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<OrderInfoDO> orderInfoList = orderInfoService.list(query);
		int total = orderInfoService.count(query);
		PageUtils pageUtils = new PageUtils(orderInfoList, total);
		return pageUtils;
	}
	
	@GetMapping("/fx/orderInfo/add")
	@RequiresPermissions("fx:orderInfo:add")
	String add(){
	    return "fx/orderInfo/add";
	}

	@GetMapping("/fx/orderInfo/edit/{orderId}")
	@RequiresPermissions("fx:orderInfo:edit")
	String edit(@PathVariable("orderId") long orderId,Model model){
		OrderInfoDO orderInfo = orderInfoService.get(orderId);
		model.addAttribute("orderInfo", orderInfo);
	    return "fx/orderInfo/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/fx/orderInfo/save")
	@RequiresPermissions("fx:orderInfo:add")
	public R save( OrderInfoDO orderInfo){
		if(orderInfoService.save(orderInfo)>0){
			return R.ok();
		}
		return R.error();
	}

	@GetMapping("/fx/orderInfo/shipView/{orderId}")
	@RequiresPermissions("fx:orderInfo:ship")
	String shipView(@PathVariable("orderId") long orderId,Model model){
		model.addAttribute("orderId",orderId);
		return "fx/orderInfo/ship";
	}

	/**
	 * 发货
	 */
	@ResponseBody
	@PostMapping("/fx/orderInfo/ship")
	@RequiresPermissions("fx:orderInfo:ship")
	public R ship( OrderInfoDO orderInfo){
		if(orderInfoService.ship(orderInfo)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/fx/orderInfo/update")
	@RequiresPermissions("fx:orderInfo:edit")
	public R update( OrderInfoDO orderInfo){
		orderInfoService.update(orderInfo);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/fx/orderInfo/remove")
	@ResponseBody
	@RequiresPermissions("fx:orderInfo:remove")
	public R remove( Long orderId){
		if(orderInfoService.remove(orderId)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/fx/orderInfo/batchRemove")
	@ResponseBody
	@RequiresPermissions("fx:orderInfo:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] orderIds){
		orderInfoService.batchRemove(orderIds);
		return R.ok();
	}

	/*
    * 个人订单列表
    * */
	@RequestMapping("/wx/orderInfo/listPersonalOrders")
	@ResponseBody
	public JsonResult listPersonalOrders(String state,String userId,HttpServletRequest request,HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		//UserInfoDO userInfo = (UserInfoDO) request.getSession().getAttribute("userInfo");
		if(userId != null && userId.length() > 0){
			Map<String,Object> map = new HashMap<>();
			map.put("userId",userId);
			if(state != null && state.length() > 0){
				map.put("orderStatus",state);
			}
			List<Map<String,Object>> lsit = orderInfoService.listOrders(map);
			return ResultUtil.renderSuccess(lsit);
		}
		return ResultUtil.renderError("返回结果为空！");
	}

	/*
    * 从购物车提交订单
    * @param orderInfo：订单实体类，
    * shopCertIds：购物车列表id（使用逗号“,”隔开），
    * addressId：地址id
    * */
	@RequestMapping("/wx/orderInfo/submitOrder")
	@ResponseBody
	public void submitOrder( String orderId, String addressId, HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		OrderInfoDO orderInfo = orderInfoService.get(Long.parseLong(orderId));
		UserAddressDO userAddress = userAddressService.get(Long.parseLong(addressId));
		String detailAddr = userAddress.getAddrProvince() + "_" +
				userAddress.getAddrCity() + "_" +
				userAddress.getAddrArea() + ",详细地址：" +
				userAddress.getAddrAddress();
		orderInfo.setOrderAddress(detailAddr);
		orderInfo.setReceiverTel(userAddress.getAddrTel());
		//orderInfo.setReceiverName(userAddress.getAddrReceiver());
		//boolean b = orderInfoService.submitOrder(orderInfo,userInfo,shopCertIds,addressId);
		int b = orderInfoService.update(orderInfo);
		String url = request.getRequestURL().toString();
		String[] s = url.split("/wx/");
		if(b>0){
			//response.sendRedirect(s[0] + "/wx/payOrder?orderId" + orderId);
			request.getRequestDispatcher("/wx/payOrder?orderId" + orderId).forward(request,response);
		}else{
			response.sendRedirect(s[0] + "/dist/index.html?userId=" + orderInfo.getUserId());
		}
	}


	/*
    * 从购物车提交订单
    * @param orderInfo：订单实体类，
    * shopCertIds：购物车列表id（使用逗号“,”隔开），
    * addressId：地址id
    * */
	@RequestMapping("/wx/orderInfo/submitOrder2")
	@ResponseBody
	public JsonResult submitOrder2( String shopCertIds,String userId, HttpServletResponse response, HttpServletRequest request){
		response.setHeader("Access-Control-Allow-Origin", "*");
		//UserInfoDO userInfo = (UserInfoDO) request.getSession().getAttribute("userInfo");
		String ip = IPUtils.getIpAddr(request);

		OrderInfoDO orderInfo = new OrderInfoDO();
		orderInfo.setUserIp(ip);
		OrderInfoDO b = orderInfoService.submitOrder2(orderInfo,userInfoService.get(Long.parseLong(userId)),shopCertIds);
		Map<String,Object> map = new HashMap<>();
		map.put("orderId",b.getOrderId());
		return ResultUtil.renderSuccess(orderInfoService.listOrders(map));
	}



	/*
    * 直接购买
    * @param orderInfo：订单实体类，
    * shopCertIds：购物车列表id（使用逗号“,”隔开），
    * addressId：地址id
    * */
	@RequestMapping("/wx/orderInfo/buyOrder")
	@ResponseBody
	public JsonResult buyOrder( String goodId,String num,String userId,HttpServletResponse response, HttpServletRequest request){
		response.setHeader("Access-Control-Allow-Origin", "*");
		//UserInfoDO userInfo = (UserInfoDO) request.getSession().getAttribute("userInfo");
		String ip = IPUtils.getIpAddr(request);
		if(userId == null && userId.length() == 0){
			return ResultUtil.renderError();
		}

		OrderInfoDO orderInfo = new OrderInfoDO();
		orderInfo.setUserIp(ip);
		OrderInfoDO b = orderInfoService.buyOrder(orderInfo,userInfoService.get(Long.parseLong(userId)),goodId,num);
		Map<String,Object> map = new HashMap<>();
		map.put("orderId",b.getOrderId());
		return ResultUtil.renderSuccess(orderInfoService.listOrders(map));
	}


	@RequestMapping("/wx/orderInfo/autoOrder")
	@ResponseBody
	public void autoOrder(HttpServletResponse response, HttpServletRequest request){
		response.setHeader("Access-Control-Allow-Origin", "*");
		orderInfoService.aotuBalanceOrders();
	}

	@RequestMapping("/wx/orderInfo/deleteOrder")
	@ResponseBody
	public R deleteOrder(String orderId,HttpServletResponse response, HttpServletRequest request){
		response.setHeader("Access-Control-Allow-Origin", "*");
		if(orderId != null && orderId.length() > 0) {
			int num = orderInfoService.remove(Long.parseLong(orderId));
			if(num > 0){
				return R.ok();
			}else{
				return R.error();
			}
		}else{
			return R.error("参数错误！");
		}
	}



}
